package com.example.im.mvp.presenter

import android.app.ProgressDialog
import android.content.Context
import com.example.im.app.ImApplication
import com.example.im.bean.InviteCode
import com.example.im.common.Constants
import com.example.im.xmpp.IMConnection
import com.example.im.mvp.base.BasePresenter
import com.example.im.mvp.view.IAccessView
import com.example.im.db.DatabaseStorage
import com.example.im.http.APIRetrofit
import com.example.im.http.RetrofitManager
import com.example.im.utils.ACache
import com.example.im.utils.LogUtils
import com.example.im.utils.RandomUntil
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import java.util.AbstractMap

class AccessPresenter(mContext: Context, mView: IAccessView?) :
    BasePresenter<IAccessView>(mContext, mView) {

    private var dialog: ProgressDialog? = null
    private var imConnection: IMConnection? = null

    init {
        dialog = ProgressDialog(mContext)
        dialog!!.setCanceledOnTouchOutside(false)
        dialog!!.setMessage("请稍候...")

        imConnection = IMConnection.instance
    }

    override fun detachView() {
        super.detachView()
        this.disposable.clear()
    }

    fun userLogin(userName: String, userPwd: String) {

        if (userName.isEmpty()) {
            getView().onHint("请输入用户名")
            return
        }
        if (userPwd.isEmpty()) {
            getView().onHint("请输入用户密码")
            return
        }

        val disposables: Disposable = Observable
            .just(AbstractMap.SimpleEntry<String, String>(userName, userPwd))
            .flatMap({
                Observable.just(imConnection?.connectLogin(it.key, it.value) ?: false)
            }, { t1, t2 ->
                if (t2)
                    DatabaseStorage.setAccountAndPassword(t1.key, t1.value)
                t2
            })
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(
                {
                    if (it) getView().onLoginSuccess()
                },
                { error ->
                    getView().onHint(error.message!!)
                    dialog!!.cancel()
                },
                { dialog!!.cancel() },
                { dialog!!.show() }
            )
        this.disposable.add(disposables)

    }

    fun userSignUp(name: String, userPwd: String, code: String) {

        if (name.isEmpty()) {
            getView().onHint("请输入昵称")
            return
        }
        if (userPwd.isEmpty()) {
            getView().onHint("请输入密码")
            return
        }
        if (userPwd.length < 6) {
            getView().onHint("用户密码不能少于6位数")
            return
        }
        if (code.isEmpty()) {
            getView().onHint("请输入邀请码")
            return
        }

        val disposables: Disposable = Observable.just(mutableMapOf("inviteCode" to code))
            .subscribeOn(Schedulers.io())
            .flatMap {
                RetrofitManager.retrofit().create(APIRetrofit::class.java)
                    .getInviteCode(it)
                    .onErrorReturn {
                        with(InviteCode(), {
                            this.code = -1
                            this.data = null
                            this
                        })
                    }
            }
            .map {
                !(it.code != 0 || it.data == null)
            }
            .observeOn(AndroidSchedulers.mainThread())
            .filter {
                if (!it) {
                    getView().onHint("注册失败，验证码错误！")
                }
                return@filter it
            }
            .subscribeOn(Schedulers.io())
            .map {
                imConnection!!.setAccountCreate(name, userPwd)
            }
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(
                {
                    if (it.isEmpty())
                        getView().onHint("注册失败")
                    else {
                        getView().onLogonSuccess(it)
                        val preferences = ImApplication.context()
                            .getSharedPreferences(
                                Constants.ACCOUNT_ATTRIBUTES,
                                Context.MODE_PRIVATE
                            )
                        val editor = preferences.edit()
                        editor.putString(Constants.ACCOUNT_USER_NAME, it)
                        editor.apply()
                    }
                },
                { error ->
                    getView().onHint(error.message!!)
                    dialog!!.cancel()
                },
                { dialog!!.cancel() },
                { dialog!!.show() }
            )
        this.disposable.add(disposables)
    }
}